<template>
  <el-form
    ref="userInfoForm"
    class="qm-table-form"
    :model="models"
    :rules="rules"
    label-width="120px"
  >
    <el-tabs style="height: 500px;">
      <el-tab-pane label="账号信息">
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录账号：" prop="model.loginId">
              <el-input v-model="models.model.loginId" :disabled="pageAction != 'create'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名：" prop="model.userName">
              <el-input v-model="models.model.userName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户类型：" prop="model.userType">
              <el-select v-model="models.model.userType">
                <el-option
                  v-for="item in controlData.userTypes"
                  :key="item.name"
                  :value="item.name"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="选择部门：" prop="model.departmentId">
              <el-cascader
                v-model="models.model.departmentId"
                clearable
                placeholder="请选择"
                :options="controlData.deptTree"
                :show-all-levels="false"
                :props="{ value: 'id', label: 'text', checkStrictly: true }"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户等级(用于工作流选人排序)：" prop="model.userLevel">
              <el-input v-model="models.model.userLevel" placeholder="用于工作流选人排序" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="启用账号：" prop="model.isEnabled">
              <el-radio v-model="models.model.isEnabled" :label="true">是</el-radio>
              <el-radio v-model="models.model.isEnabled" :label="false">否</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="锁定账号：" prop="model.isLocked">
              <el-radio v-model="models.model.isLocked" :label="true">是</el-radio>
              <el-radio v-model="models.model.isLocked" :label="false">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="个人信息">
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别：" prop="profile.gender">
              <el-radio v-model="models.profile.gender" :label="0">男</el-radio>
              <el-radio v-model="models.profile.gender" :label="1">女</el-radio>
            </el-form-item>
            <el-form-item label="手机号码：" prop="profile.mobile">
              <el-input v-model="models.profile.mobile" />
            </el-form-item>
            <el-form-item label="电子邮箱：" prop="profile.email">
              <el-input v-model="models.profile.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="8" style="text-align: center;">
                个人图像：
                <br />(jpg格式，2M以内)
              </el-col>
              <el-col :span="16">
                <el-upload
                  class="avatar-uploader"
                  :action="getUploadUrl(models.profile.photoUrl)"
                  :show-file-list="false"
                  :on-success="
                    (res, file, fileList) => handleAvatarSuccess(res, models)
                  "
                  :before-upload="beforeAvatarUpload"
                >
                  <img
                    v-if="models.profile.photoUrl"
                    style="border: 1px dashed #ccc;border-radius: 6px;"
                    :src="avatar"
                    class="avatar"
                    :onerror="loadFailProfile"
                  />
                  <i
                    v-else
                    class="el-icon-plus avatar-uploader-icon"
                    style="border: 1px dashed #ccc; border-radius: 6px;"
                  />
                </el-upload>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号码：" prop="profile.cardId">
              <el-input v-model="models.profile.cardId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期：" prop="profile.birthday">
              <el-date-picker
                v-model="models.profile.birthday"
                type="date"
                default-value="1980-01-01"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="任职职位：" prop="profile.position">
              <el-input v-model="models.profile.position" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="入职日期：" prop="profile.joinDate">
              <el-date-picker
                v-model="models.profile.joinDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="联系地址：" prop="profile.address">
              <el-input v-model="models.profile.address" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注：" prop="profile.memo">
              <el-input v-model="models.profile.memo" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="个人证照">
        <qm-uploader
          :data-key="models.model.userId || ''"
          :categories="['个人证照']"
          :is-show-upload="true"
          :upload-files="uploadSuccessFiles"
        />
      </el-tab-pane>
    </el-tabs>

    <el-row>
      <el-col :span="24" style="text-align: right;">
        <el-button type="primary" size="medium" @click="save">保存</el-button>
        <el-button size="medium" @click="$emit('modal-close')">取消</el-button>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import request from "@/utils/request";
import _ from "lodash";
import QmUploader from "@/libs/components/qm-uploader";
import { mapGetters } from "vuex";

export default {
  name: "AdminSysUserProfile",
  components: {
    QmUploader,
  },
  props: {
    models: Object,
    controlData: Object,
    pageAction: String,
  },
  data() {
    return {
      row: {},
      uploadSuccessFiles: [],
      checkPassError: "",
      rules: {
        "model.userName": [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
        "model.loginId": [
          { required: true, message: "请输入登录账号", trigger: "blur" },
        ],
        // "profile.mobile": [
        //   {
        //     required: true,
        //     message: "请输入手机号",
        //     trigger: "blur",
        //   },
        // ],
      },
      loadFailProfile:
        'this.src="' + require("@/assets/images/profile.png") + '"',
    };
  },
  computed: {
    ...mapGetters(["avatar"]),
  },
  methods: {
    save() {
      this.$refs["userInfoForm"].validate((valid) => {
        if (valid) {
          const postModel = _.cloneDeep(this.models);
          postModel.pageAction = "edit";
          postModel.userId = postModel.model.userId;
          request.post("/admin/sysUser/save", postModel).then((r) => {
            if (r && r.success) {
              this.notifySuccess(r.message || "修改信息成功");
              this.$emit("modal-close");
            } else {
              this.notifyError(r.message || "修改用户信息失败");
            }
          });
        } else {
          this.notifyError("表单校验不通过，请检查表单内容");
        }
      });
    },
    checkPwd(checkPass, password) {
      if (checkPass !== password) {
        this.checkPassError = "两次密码必须一致";
      } else {
        this.checkPassError = "";
      }
    },
    uploadSuccess(attachment) {
      if (this.pageAction === "create") {
        this.uploadSuccessFiles.push(attachment.attachmentId);
      }
    },
    getUploadUrl(attachmentId) {
      return `${
        process.env.VUE_APP_BASE_API
      }/attachment/upload?type=picture&attachmentId=${
        attachmentId || ""
      }&isTemp=${!attachmentId}`;
    },
    handleAvatarSuccess(res, models) {
      if (this.models && this.models.profile) {
        const avatar =
          models.profile && models.profile.photoUrl
            ? `${
                process.env.VUE_APP_BASE_API
              }/attachment/download?attachmentId=${
                models.profile.photoUrl
              }&rnd=${Math.random()}`
            : require("@/assets/images/profile.png");
        this.$store.dispatch("setAvatar", avatar);
      }
    },
    beforeAvatarUpload(file) {
      // 控制上传的大小及格式
      // ie不支持const let
      /* const isJPG = file.type === 'image/jpeg';
                    const isLt2M = file.size / 1024 / 1024 < 2;*/
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  line-height: 160px;
  text-align: center;
}
.avatar {
  width: 160px;
  height: 160px;
  display: block;
}
</style>
